<?php

namespace think\wework\Api;

use GuzzleHttp\Exception\GuzzleException;
use think\wework\Abstracts\WeworkApiWithToken;

class GroupSend extends WeworkApiWithToken
{
    private static ?GroupSend $instance = null;

    public static function getInstance(): GroupSend
    {
        if (!self::$instance instanceof GroupSend) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 创建企业群发
     * @param string $chat_type
     * @param array $sender
     * @param string $message
     * @param array $attachments
     * @return array
     * @throws GuzzleException
     */
    public function send(string $chat_type = 'single', array $sender = [], string $message = '', array $attachments = []): array
    {
        $json = [
            'chat_type' => $chat_type,
            'sender' => $sender,
            'text' => [
                'content' => $message
            ]
        ];
        if (!empty($attachments)) $json['attachments'] = $attachments;
        return $this->httpClient->post('externalcontact/add_msg_template', compact('json'))->toArray();
    }

    /**
     * 获取群发记录列表
     * @param string $chat_type
     * @param int $start_time
     * @param int $end_time
     * @param string $cursor
     * @return array
     * @throws GuzzleException
     */
    public function history(string $chat_type,int $start_time, int $end_time, string $cursor = ''): array
    {
        $json = [
            'chat_type' => $chat_type,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'limit' => 100,
            'cursor' => $cursor
        ];
        return $this->httpClient->post('externalcontact/get_groupmsg_list_v2', compact('json'))->toArray();
    }

    /**
     * 获取群发成员发送任务列表
     * @param string $msgId
     * @param string $cursor
     * @return array
     * @throws GuzzleException
     */
    public function task(string $msgId, string $cursor = ''): array
    {
        $json = [
            'msgid' => $msgId,
            'limit' => 1000,
            'cursor' => $cursor
        ];
        return $this->httpClient->post('externalcontact/get_groupmsg_task', compact('json'))->toArray();
    }

    /**
     * 获取企业群发成员执行结果
     * @param string $msgId
     * @param string $userId
     * @param string $cursor
     * @return array
     * @throws GuzzleException
     */
    public function result(string $msgId, string $userId, string $cursor = ''): array
    {
        $json = [
            'msgid' => $msgId,
            'userid' => $userId,
            'limit' => 1000,
            'cursor' => $cursor
        ];
        return $this->httpClient->post('externalcontact/get_groupmsg_send_result', compact('json'))->toArray();
    }
}
